package others.swing.p024;

import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;

class ShowBook extends JDialog implements ItemListener {
    JTable table;
    Object a[][];
    Object name[] = {"编号", "书名", "出版社", "出版日期"};
    JCheckBox showBook;

    ShowBook() {
        showBook = new JCheckBox("显示信息");
        showBook.addItemListener(this);
        add(showBook, BorderLayout.NORTH);
        setBounds(200, 200, 500, 500);
        setVisible(true);
    }

    @Override
    public void itemStateChanged(ItemEvent e) {
        JCheckBox box = (JCheckBox) e.getItemSelectable();
        if (box.isSelected()) {
            Connection con;
            Statement sql;
            ResultSet rs;
            try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            } catch (ClassNotFoundException ee) {
                System.out.println("" + ee);
            }
            try {
                con = DriverManager.getConnection(Main.DB_URL, Main.DB_USER_NAME, Main.DB_PASSWORD);
                sql = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
                rs = sql.executeQuery("SELECT * FROM insertBook");
                rs.last();
                int lastNumber = rs.getRow();
                a = new Object[lastNumber][4];
                int k = 0;
                rs.beforeFirst();
                while (rs.next()) {
                    a[k][0] = rs.getString(1);
                    a[k][1] = rs.getString(2);
                    a[k][2] = rs.getString(3);
                    a[k][3] = rs.getString(4);
                    k++;
                }
                con.close();
            } catch (SQLException ee) {
                System.out.println(ee);
            }
            table = new JTable(a, name);
            getContentPane().removeAll();
            add(showBook, BorderLayout.NORTH);
            add(new JScrollPane(table), BorderLayout.CENTER);
            setVisible(true);
            validate();
        } else {
            table.setVisible(false);
        }
    }
}
